<?php declare(strict_types=1);
/**
 * @author      xianganyall <xianganyall@gmail.com>
 * @copyright   2023-2025 owner
 **/

namespace Srv\Libs\Frame;

use Swoole\WebSocket\Server;

abstract class TaskAbstract
{
    private bool $isInit                    = false;    // 是否已初始化
    private bool $isTask                    = false;    // 是否已配置任务
    protected string $envStr                = '';       // 初始化的环境数据[JSON]

    /**
     * @param Server|null $WebSocketServer
     * @return void
     * init
     */
    final public function init(?Server $WebSocketServer):void
    {
        if($this->isInit) return;
        $this->isInit   = true;
        if(strlen($this->envStr) < 3 || !EnvData::initFrom($this->envStr)) EnvData::init([], [], [], [], [], [], [], [], '', 1);
    }

    /**
     * @return void
     * task
     */
    final public function task():void
    {
        if($this->isTask) return;
        $this->isTask       = true;
        $WebSocketServer    = ResponseMain::getWebSocketServer();
        if($WebSocketServer instanceof Server) $WebSocketServer->task($this);
    }

    /**
     * @return void
     * taskRun
     */
    final public function taskRun():void
    {
        $WebSocketServer    = ResponseMain::getWebSocketServer();
        if(($WebSocketServer instanceof Server) && !$WebSocketServer->taskworker){  // 不是Task进程
            if($this->isTask) return;
            $this->isTask   = true;
        }
        $this->init($WebSocketServer);
        $this->runBefore($WebSocketServer);
        $this->run($WebSocketServer);
        $this->runAfter($WebSocketServer);
    }

    /**
     * @return bool
     * isTask
     */
    final public function isTask():bool
    {
        return $this->isTask;
    }

    /**
     * @param Server|null $WebSocketServer
     * @return void
     * runBefore
     */
    abstract public function runBefore(?Server $WebSocketServer):void;

    /**
     * @param Server|null $WebSocketServer
     * @return void
     * run
     */
    abstract public function run(?Server $WebSocketServer):void;

    /**
     * @param Server|null $WebSocketServer
     * @return void
     * runAfter
     */
    abstract public function runAfter(?Server $WebSocketServer):void;

    /**
     * @param string $envStr
     * @param int $delayTimeMill
     * @return static
     * create
     */
    abstract public static function create(string $envStr, int $delayTimeMill):self;
}